<template>
    <div class='edit-popup'>
        <popup
            ref='popupRef'
            :title='popupTitle'
            :async='true'
            width='850px'
            @confirm='handleSubmit'
            @close='handleClose'
        >
            <div class='popup-container'>
                <el-tabs v-model='activeName' class='demo-tabs'>
                    <el-tab-pane label='基本信息' name='detail'>
                        <el-form label-position='left' ref='formRef' :model='formData' label-width='90px'
                                 :rules='formRules'>
                            <el-form-item label='酒店名称' prop='hotel_name'>
                                <el-input v-model='formData.hotel_name' clearable placeholder='请输入酒店名称' />
                            </el-form-item>
                            <el-form-item label='城市' prop='city_id'>
                                <el-cascader style='width:280px;' v-model='formData.city_id'
                                             :options='cityData' />
                            </el-form-item>
                            <el-form-item label='酒店地址' prop='addr'>
                                <el-input v-model='formData.addr' clearable placeholder='请输入酒店地址' />
                            </el-form-item>
                            <el-form-item label='经纬度' prop='location'>
                                <el-input v-model='formData.location' clearable
                                          placeholder='请输入经纬度(直接将复制的经纬度粘贴到此处即可)'>
                                    <template #append>
                                        <el-button type='danger' @click='getLocation'>获取坐标</el-button>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item label='图片' prop='cover_imag'>
                                <material-picker :limit='1' v-model='formData.cover_imag' type='image' />
                            </el-form-item>
                            <el-form-item label='内容' prop='content'>
                                <editor v-model='formData.content' :height='500' :width='680' />
                            </el-form-item>
                            <el-form-item label='商家id' prop='user_id'>
                                <el-select placeholder='请选择对应商家' v-model='formData.user_id'>
                                    <el-option v-for='(item,index) in shopList' :key='index' :value='item.id'
                                               :label='item.name' />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label='房型设置' name='room'>
                        <div class='room-type-container'>
                            <div class='empty-wrap' v-if='!roomTypeList.length'>
                                <span>暂未添加房型...</span>
                            </div>
                            <div v-else>
                                <div v-for='(item,index) in roomTypeList' :key='index' class='type-item'>
                                    <el-descriptions
                                        border
                                        :title='item.name'
                                    >
                                        <template #extra>
                                            <el-space>
                                                <el-button type='primary' @click='editType(item,index)' :icon='Edit'
                                                           circle />
                                                <el-button @click='removeType(index)' type='danger' :icon='Delete'
                                                           circle />
                                            </el-space>
                                        </template>
                                        <el-descriptions-item>
                                            <template #label>
                                                <span>价格</span>
                                            </template>
                                            <span>{{ item.price }}</span>
                                        </el-descriptions-item>
                                        <el-descriptions-item>
                                            <template #label>
                                                <span>数量</span>
                                            </template>
                                            <span>{{ item.number }}</span>
                                        </el-descriptions-item>
                                    </el-descriptions>
                                </div>
                            </div>
                            <div class='add-btn'>
                                <el-button @click='addRoomType' style='width: 100%;border-style: dashed;' type='primary'
                                           plain>添加房型
                                </el-button>
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
            <room-type v-model='showDialog' ref='typeRef' @edit='editTypeHandle' @success='addTypeSuccess' />
        </popup>
    </div>
</template>

<script lang='ts' setup name='hotelEdit'>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiHotelAdd, apiHotelDetail, apiHotelEdit, apiShopList } from '@/api/hotel'
import type { PropType } from 'vue'
import { getCity, getCityNew } from '@/api/article'
import RoomType from './room-type.vue'
import { Delete, Edit } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})

const typeRef = ref(null)

const shopList = ref([])

async function initShopList() {
    shopList.value = await apiShopList() || []
}

function editTypeHandle(value: any) {
    const { index, name, number, price } = value
    if (!roomTypeList.value[index]) return
    roomTypeList.value[index] = {
        name, number, price
    }
    showDialog.value = false
}

function addTypeSuccess(data: any) {
    const { name, number, price } = data
    roomTypeList.value.push({ name, number, price })
    showDialog.value = false
}

function editType(item: any, index: number) {
    typeRef.value?.editItem(item, index)
    showDialog.value = true
}

function removeType(index: number) {
    roomTypeList.value.splice(index, 1)
}

function addRoomType() {
    showDialog.value = true
}

const showDialog = ref(false)
const roomTypeList = ref<any>([])
const activeName = ref('detail')
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')


// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑酒店管理' : '新增酒店管理'
})

// 表单数据
const formData = reactive({
    id: '',
    hotel_name: '',
    city_id: '',
    addr: '',
    lng: '',
    lat: '',
    content: '',
    user_id: '',
    location: '',
    cover_imag: ''
})

function getLocation() {
    window.open('https://lbs.qq.com/getPoint/')
}

const cityData = ref([])

initCityData()

async function initCityData() {
    const resp = await getCityNew({})
    if (!resp || !resp.length) return

    function patchMap(v: any) {
        if (!v.hasOwnProperty('children')) return
        if (!v.children || !v.children.length) return
        return v.children.map((item: any) => {
            const { id, name } = item
            const data = {
                value: id, label: name
            }
            const children = patchMap(item)
            if (children) data.children = children
            return data
        })
    }

    cityData.value = resp.map((item: any) => {
        const { id, name, children } = item
        return {
            label: name, value: id, children: patchMap(item)
        }
    })
    console.log(cityData,'cityData')
}


// 表单验证
const formRules = computed(() => {
    return {
        hotel_name: [
            {
                required: true,
                message: '请输入酒店名称',
                trigger: 'blur'
            }
        ],
        city_id: [
            {
                required: true,
                message: '请选择对应城市',
                trigger: 'blur'
            }
        ],
        addr: [
            {
                required: true,
                message: '请输入酒店地址',
                trigger: 'blur'
            }
        ],
        location: [
            {
                required: true,
                message: '请输入经纬度',
                trigger: 'blur'
            },
            {
                validator: (rules: any, value: string, callback: any) => {
                    if (!value) return callback(new Error('请输入经纬度'))
                    const locationArr = value.split(',')
                    if (!locationArr || !Array.isArray(locationArr) || locationArr.length !== 2) return callback(new Error('经纬度使用英文输入法的逗号分隔'))
                    const [lng, lat] = locationArr
                    if (!lng || !lat) return callback(new Error('请输入合法的经纬度'))
                    callback()
                },
                trigger: 'blur'
            }
        ],
        content: [
            {
                required: true,
                message: '请输入酒店介绍',
                trigger: 'blur'
            }
        ],
        user_id: [
            {
                required: true,
                message: '请选择对应商家'
            }
        ],
        cover_imag: [
            {
                required: true,
                message: '请上传图片',
                trigger: 'blur'
            }
        ]
    }
})
// 获取详情
const setFormData = async (data: any) => {
    console.log(data, 'data')
    const baseKeys = ['hotel_name', 'addr', 'content', 'user_id', 'cover_imag', 'id']
    baseKeys.forEach(key => {
        formData[key] = data[key] || ''
    })
    const { lat, lng, types,province, city_id, area } = data
    formData.location = `${lat},${lng}`
    formData.city_id = [province,city_id,area]
    let list = []
    if (types.length) {
        list = types.map((item: any) => {
            const { name, price, number } = item
            return { name, price, number }
        })
    }
    roomTypeList.value = list
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiHotelDetail({
        id: row.id
    })
    setFormData(data)
}

/**
 *  hotel_name: '',
 *   city_id: '',
 *   addr: '',
 *   lng: '',
 *   lat: '',
 *   content: '',
 *   user_id: '',
 *   location: '',
 */
function getPayload() {
    const {
        hotel_name, city_id, addr, location, content, user_id, cover_imag
    } = formData
    const [lat, lng] = location.split(',')
    return {
        hotel_name, city_id, addr, content, user_id, lng, lat,
        types: roomTypeList.value.map(item => item), cover_imag
    }
}

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    if (!roomTypeList.value.length) {
        activeName.value = 'room'
        return ElMessage({
            message: '请添加房型',
            type: 'error'
        })
    }
    const payload = getPayload()
    if (mode.value === 'edit') {
        payload.id = formData.id
    }
    mode.value == 'edit'
        ? await apiHotelEdit(payload)
        : await apiHotelAdd(payload)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
    initShopList()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}


defineExpose({
    open,
    setFormData,
    getDetail
})
</script>

<style lang='scss' scoped>
.popup-container {
    width: 100%;
    height: 620px;
    padding-right: 8px;
    overflow-y: scroll;
    box-sizing: border-box;

    .add-btn {
        padding: 24px 0;
    }

    .type-item {
        margin-bottom: 24px;

        &:last-child {
            margin-bottom: 0;
        }
    }

    &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
    }

    &::-webkit-scrollbar-thumb {
        border-radius: 10px;
        box-shadow: inset 0 0 5px rgba(236, 236, 236, 0.1);
        background: #ccc;
    }

    &::-webkit-scrollbar-track {
        box-shadow: inset 0 0 5px rgba(236, 236, 236, 0.1);
        border-radius: 10px;
        background: #ededed;
    }
}
</style>
